// Wordaddfragment.kt
package com.example.sunchaodong

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import androidx.fragment.app.Fragment
import androidx.fragment.app.commit
import androidx.fragment.app.replace

class Wordaddfragment : Fragment() {
    private lateinit var wordFileHelper: WordFileHelper

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_word_add, container, false)
        wordFileHelper = WordFileHelper(requireContext())

        val wordInput: EditText = view.findViewById(R.id.word_input)
        val confirmButton: Button = view.findViewById(R.id.confirm_button)
        confirmButton.setOnClickListener {
            val newWord = wordInput.text.toString()
            if (newWord.isNotEmpty()) {
                val words = wordFileHelper.readWordsFromFile().toMutableList()
                val index = words.indexOfFirst { it.isEmpty() }
                if (index != -1) {
                    words[index] = newWord
                } else {
                    words.add(newWord)
                }
                wordFileHelper.saveWordsToFile(words)
                activity?.supportFragmentManager?.commit {
                    replace<Wordfragment>(R.id.fragment_container_view)
                    addToBackStack(null)
                }
            }
        }

        val homeButton: Button = view.findViewById(R.id.home_button)
        homeButton.setOnClickListener {
            activity?.supportFragmentManager?.popBackStack()
            (activity as? MainActivity)?.showMainActivityViews()
        }

        return view
    }
}